package com.zliuyno.rpcdemo.transport;

import com.zliuyno.rpcdemo.util.Packmsg;
import com.zliuyno.rpcdemo.rpc.Protocol.MyContent;
import com.zliuyno.rpcdemo.rpc.Protocol.MyHeader;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.List;

public class ServerDecode extends ByteToMessageDecoder {
    //父类里一定有channelRead被调起，
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf buf, List<Object> out) throws Exception {
//        System.out.println("channel start:" + buf.readableBytes());
        while (buf.readableBytes() >= 111) {
            byte[] bytes = new byte[111];
            buf.getBytes(buf.readerIndex(), bytes);  //读取内容时指针不发生移动
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            ObjectInputStream oin = new ObjectInputStream(in);
            MyHeader header = (MyHeader) oin.readObject();
//            System.out.println("server response @ id:" + header.getRequestID());

            //server端代码  取body
            //通信协议 Decode两个方向都在使用
            if (buf.readableBytes()-111 >= header.getDataLen()) {
                buf.readBytes(111); //移动指针到body开始的位置
                byte[] data = new byte[(int) header.getDataLen()];
                buf.readBytes(data);
                ByteArrayInputStream din = new ByteArrayInputStream(data);
                ObjectInputStream doin = new ObjectInputStream(din);

                if (header.getFlag() == 0x14141414) {
                    MyContent content = (MyContent) doin.readObject();
                    out.add(new Packmsg(header, content));
                } else if (header.getFlag() == 0x14141424) {
                    MyContent content = (MyContent) doin.readObject();
                    out.add(new Packmsg(header, content));
                } else {
                    System.out.println("难道你在这？");
                }
            } else {
                break;
            }
        }
    }
}
